package study.eggs.validation.validator;

import com.google.common.primitives.Longs;
import lombok.extern.slf4j.Slf4j;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 范围验证器
 * （1）Short Integer Long Double Float
 * （2）Bigdecmal
 * （3）
 */
@Slf4j
public class RangeValidator implements Validator {

    private static final List<Class> SUPPORT_LT = Arrays.asList(Short.class,
            Integer.class,
            Long.class);

    @Override
    public boolean support(Class<?> clazz) {
        boolean flag = SUPPORT_LT.stream()
                .anyMatch(e -> e == clazz);
        return flag;
    }

    @Override
    public void validate(String name, Object value, Annotation annot) {
        Range range = (Range) annot;
        //非空
        if (range.required() && Objects.isNull(value)) {
            throw new RuntimeException(String.format("参数值为空[%s]", name));
        }
        //范围
        if (!Objects.isNull(value)) {
            long myValue = Longs.tryParse(value.toString());
            long min = range.min(), max = range.max();
            if (myValue < min || myValue > max) {
                throw new RuntimeException(String.format("参数值非法[%s]", name));
            }
        }
    }
}
